﻿/*
 * Created by SharpDevelop.
 * User: cansik
 * Date: 26.01.2011
 * Time: 09:53
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

using TM.TMObjects;

namespace TM.Unofficial.Chat.History
{
	/// <summary>
	/// Description of ChatParser.
	/// </summary>
	public class ChatHistory
	{
		/// <summary>
		/// History Partner
		/// </summary>
		public Member Partner{get; private set;}
		/// <summary>
		/// Chat Messages
		/// </summary>
		public List<ChatMessage> Messages{get; private set;}
		
		/// <summary>
		/// Creates a new Chat Parser
		/// </summary>
		public ChatHistory()
		{
		}
		
		/// <summary>
		/// Splits up the messages
		/// </summary>
		/// <param name="chatxml">Xml CData form History</param>
		public void ParseChatXML(string chatxml)
		{
			//Orig Regex String: <p class="[t|c_m|c_f]+">((?<datum>[0-9\.\s:]*)</p><p class="c_[f|m] showtime">)*([<a|<ahref="/\s\w\d]*)>(?<partner>[\w\d]*):</a>\s(?<message>[\w\s\d\.äöü?_-:;,!]*)</p>
			this.Messages = new List<ChatMessage>();
			
			string MessageCapturePattern = "<p class=\"[t|c_m|c_f]+\">((?<datum>[0-9\\.\\s:]*)</p><p class=\"c_[f|m] showtime\">)*([<a|<ahref=\"/\\s\\w\\d]*)>(?<partner>[\\w\\d]*):</a>\\s(?<message>[\\w\\s\\d\\.äöü]*)</p>";
			MatchCollection histmatch = Regex.Matches(chatxml, MessageCapturePattern, RegexOptions.Multiline);
			
			DateTime lastdatestamp = DateTime.Now;
			
			foreach(Match msgmatch in histmatch)
			{
				DateTime dtom;
				Boolean ispartner;
				
				//neue root message mit datum
				if (msgmatch.Groups["datum"].Success)
				{
					dtom = DateTime.Parse(msgmatch.Groups["datum"].Value.Insert(6, DateTime.Now.Year.ToString()));
					lastdatestamp = dtom;
				}
				else
				{
					dtom = lastdatestamp;
				}
				
				if (msgmatch.Groups["partner"].Value.ToLower() == "ich")
				{
					ispartner = false;
				}
				else
				{
					ispartner = true;
				}
				
				this.Messages.Add(new ChatMessage(msgmatch.Groups["message"].Value, ispartner, dtom));
			}
		}
		
	}
}
